import { RcFile, UploadFile } from 'antd/es/upload';
import { isArray, isNumber, isString } from 'lodash';
import Message from '../antds/Message';

/**
 * 获取文件后缀，不带点
 */
export const getFileSuffix = (name?: string) => {
  //获取最后一个.的位置
  let index = name?.lastIndexOf('.') || -1;
  //获取后缀
  let ext = name?.slice(index + 1) ?? '';

  return ext.toLowerCase();
};

/**
 * 获取文件后缀
 */
export const getFileExt = (file: UploadFile) => {
  const name = file?.name || file?.fileName;

  return getFileSuffix(name);
};

/**
 * 获取文件名
 */
export const getFileName = (url: string) => {
  let filePath: string = url ?? '';

  if (url?.indexOf('%') > -1) {
    filePath = decodeURIComponent(url);
  }

  //获取最后一个.的位置
  let index = filePath.lastIndexOf('/');
  //获取后缀
  let name = filePath.slice(index + 1) ?? '';

  return name;
};

// 上传图片尺寸限制
export const checkImageSize = (
  file: UploadFile,
  imgWidth: number[] | number,
  imgHeight: number[] | number,
  imgScale: number[],
) => {
  // 获取文件尺寸，判断尺寸在不在规定范围之内
  return new Promise(function (resolve, reject) {
    let reader = new FileReader();

    reader.onload = (e: any) => {
      const src = e.target.result;
      // 加载图片获取图片真实宽度和高度
      const image = new Image();

      image.onload = function () {
        const width = image.width;
        const height = image.height;
        let flag = true;

        if (isNumber(imgWidth) && isNumber(imgHeight)) {
          if (width !== imgWidth || height !== imgHeight) {
            Message.error(
              `图片规格不符，请重新选择尺寸${imgWidth} * ${imgHeight}px的图片`,
            );
            flag = false;
          }
        } else if (
          isArray(imgWidth) &&
          (width < imgWidth[0] || width > imgWidth[1])
        ) {
          Message.error(
            `图片规格不符，请重新选择宽${imgWidth[0]}px ~ ${imgWidth[1]}px的图片`,
          );
          flag = false;
        } else if (
          isArray(imgHeight) &&
          (height < imgHeight[0] || height > imgHeight[1])
        ) {
          Message.error(
            `图片规格不符，请重新选择高${imgHeight[0]}px ~ ${imgHeight[1]}px的图片`,
          );
          flag = false;
        } else if (isArray(imgScale) && imgScale?.length === 2) {
          const scale = parseFloat(`${imgScale[0] / imgScale[1]}`).toFixed(2);
          const scaleTemp = parseFloat(`${width / height}`).toFixed(2);

          if (scale !== scaleTemp) {
            Message.error(
              `图片规格不符，请重新选择比例${imgScale[0]}:${imgScale[1]}的图片`,
            );
            flag = false;
          }
        }

        if (flag) {
          resolve(file);
        } else {
          reject();
        }
      };

      image.onerror = reject;
      image.src = src;
    };
    reader.readAsDataURL(file as any);
  });
};

/**
 * 校验是否是图片
 * @param file 文件对象或字符路径 UploadFile | string
 * @returns
 */
export const checkIsImage = (file: any) => {
  const fileTypeList = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif'];
  const fileImageList = ['png', 'jpg', 'jpeg', 'gif'];
  let fileSuffix = getFileExt(file as UploadFile);

  let validFile = file?.type
    ? fileTypeList.includes(file.type)
    : fileImageList.includes(fileSuffix);

  if (isString(file)) {
    fileSuffix = getFileSuffix(file as string);

    validFile = fileImageList.includes(fileSuffix);
  }

  return validFile;
};

/**
 * 上传的图片生成base64
 * @param file
 * @returns
 */
export const getFileBase64 = (file: RcFile): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result as string);
    reader.onerror = (error) => reject(error);
  });
};

/**
 * 图片文件预览
 * @param file
 * @returns
 */
export const getImagePreview = async (file: UploadFile) => {
  let src = '';

  if (file && checkIsImage(file)) {
    if (!file?.url && !file?.preview && file?.originFileObj) {
      file.preview = await getFileBase64(file?.originFileObj as RcFile);
    }

    src = file?.url || (file?.preview as string);
  }

  return src;
};
